package com.yong.common.utils;

import android.util.Log;

/**
 * @Description: 日志打印工具类
 * @Author:         yong
 * @time 2020/10/9 11:35
 * @Version:        1.0
 */
public class LogUtil {

    /**
     * 当前使用log的类名
     */
    private static String className;
    /**
     * 当前使用log的方法名
     */
    private static String methodName;
    /**
     * 当前使用log的行数
     */
    private static int lineNumber;
    /**
     * log的开关,在Application中设置，上线关闭，测试打开
     */
    private static boolean debuggable = false;

    private LogUtil() {
        throw new RuntimeException("LogUtil无法实例化");
    }

    public static void setDebuggable(boolean debuggable) {
        LogUtil.debuggable = debuggable;
    }

    private static boolean isDebuggable() {
        return !debuggable;
    }

    /**
     * 设置显示的log信息
     * @param log
     * @return
     */
    private static String createLog(String log) {
        return "====================" +
                methodName +
                "(" +
                className +
                ":" +
                lineNumber +
                ")====================" +
                log;
    }

    /**
     * 根据获取到的堆栈跟踪信息，得到当前调用这个类的类名、方法名以及行数
     * @param stackTraceElements
     */
    private static void getName(StackTraceElement[] stackTraceElements) {
        className = stackTraceElements[1].getFileName();
        methodName = stackTraceElements[1].getMethodName();
        lineNumber = stackTraceElements[1].getLineNumber();
    }

    public static void e(String msg) {
        if (isDebuggable()) {
            return;
        }
        //获取堆栈信息
        getName(new Throwable().getStackTrace());
        Log.e(className, createLog(msg));
    }

    public static void d(String msg) {
        if (isDebuggable()) {
            return;
        }
        getName(new Throwable().getStackTrace());
        Log.d(className, createLog(msg));
    }

    public static void i(String msg) {
        if (isDebuggable()) {
            return;
        }
        getName(new Throwable().getStackTrace());
        Log.i(className, createLog(msg));
    }

    public static void w(String msg) {
        if (isDebuggable()) {
            return;
        }
        getName(new Throwable().getStackTrace());
        Log.w(className, createLog(msg));
    }
}

